<?php
class StatusController extends Controller {
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array (
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
			
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
			array (
				'allow', // allow all users to perform 'index' and 'view' actions
				'actions' => array (
					'index',
					'view',
					'view1',
					'viewdetailCallHistory',
					'sendNewLetter',
					'callFollowUpPhone',
					'sendSms'
				),
				'users' => array (
					'*'
				),
				
			),
			array (
				'allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions' => array (
					'create',
					'update',
					'about'
				),
				'users' => array (
					'@'
				),
				
			),
			array (
				'allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions' => array (
					'admin',
					'delete',
					'callLoginAdmin',
					'reports'
				),
				'users' => array (
					'@'
				),
				
			),
			array (
				'deny', // deny all users
				'users' => array (
					'*'
				),
				
			),
			
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
		$this->render('view', array (
			'model' => $this->loadModel($id),
			
		));
	}

	public function actionView1() {
		$model = new Status;
		$user_id = Yii :: app()->user->id > 0 ? Yii :: app()->user->id : $_POST['Status']['agent_id'];
		if(!$user_id>0){
			$this->redirect(array (
					'site/login'
				));
		}
		if (isset ($_POST['Status'])) {
			$model->attributes = $_POST['Status'];
			$model->status = $_POST['status'];

			if ($_POST['status'] == '6') {
				$model->follow_up = $_POST['follow_up'];
				$model->sign_up_date = $_POST['sign_up_date1'];
				$model->callback_date_and_time = "";
				$model->contract_expire_date = $_POST['contract_expire_date1'];
				$model->package = $_POST['package1'];
			} else
				if ($_POST['status'] == '7') {
					$model->sign_up_date = $_POST['sign_up_date'];
					$model->callback_date_and_time = "";
					$model->contract_expire_date = $_POST['contract_expire_date'];
					$model->package = $_POST['package'];
				}
			if ($model->save())
				PotentialCustomers :: model()->updateAll(array (
					'mark' => 0
				), 'potential_customers_id=:potential_customers_id', array (
					':potential_customers_id' => $_POST['Status']['customer_id']
				));
			//			if($_POST['status']=='6')
			//			{
			//				PotentialCustomers::model()->updateAll(array('first_name'=>$_POST['first_name1'],'last_name'=>$_POST['last_name1'],'gender'=>$_POST['gender1'],'mobile'=>$_POST['mobile1'],'address'=>$_POST['address1'],'email'=>$_POST['email1'],'post_code'=>$_POST['post_code1'],'update_user'=>$user_id,'update_time'=>date("Y-m-d H:i:s")),'potential_customers_id=:potential_customers_id',array(':potential_customers_id'=>$_POST['Status']['customer_id']));
			//			}elseif($_POST['status']=='7') {
			PotentialCustomers :: model()->updateAll(array (
				'first_name' => $_POST['first_name'],
				'last_name' => $_POST['last_name'],
				'gender' => $_POST['PotentialCustomers']['gender'],
				'mobile' => $_POST['mobile'],
				'address' => $_POST['address'],
				'email' => $_POST['email'],
				'post_code' => $_POST['post_code'],
				'update_user' => $user_id,
				'update_time' => date("Y-m-d H:i:s")
			), 'potential_customers_id=:potential_customers_id', array (
				':potential_customers_id' => $_POST['Status']['customer_id']
			));
			//}
			//如果点了提交并结束的按钮则返回get user界面		
			if (isset ($_POST['stop'])) {
				$this->redirect(array (
					'about'
				));
			}
			$this->redirect(array (
				'view1'
			));

		}
		//首先找到这个销售活动

		$sqlcampaign = "SELECT * FROM  `zy_campaign` WHERE sales_people LIKE  '%" . $user_id . "%' AND zy_campaign_status =0";
		$resultcampaign = Yii :: app()->db->createCommand($sqlcampaign)->queryAll();
		$model->campaign_id = $resultcampaign[0]['zy_campaign_id'];
		if (empty ($resultcampaign))
			throw new CHttpException(404, '您没有要打的用户了.');
		$potential_customers_list_id_list = str_replace("|", ",", $resultcampaign[0]['zy_potentiel_customers_list_id']);
		$modelcustomers = $this->getOneCustomer($potential_customers_list_id_list, $resultcampaign[0]['zy_campaign_id'], $model,$user_id);
		//通过客户的手机号查询客户的中奖信息
		$surveyuser = $this->getsurveyuserinfo($modelcustomers->mobile);
		if (!$modelcustomers)
			$this->redirect('about');
		$this->render('view1', array (
			'modelcustomers' => $modelcustomers,
			'surveyuser' => $surveyuser,
			'model' => $model,
			
		));
	}

	//查看该用户的详细通话记录,并且显示这条客户的具体信息
	public function actionViewdetailCallHistory($customer_id,$campaign_id) {
		$modelpotentialcustomers = PotentialCustomers :: model()->findByPk($customer_id);
		$model = new Status('searchdetail');
		$model->unsetAttributes(); // clear any default values
		$model->customer_id=$customer_id;
		$model->campaign_id=$campaign_id;
		$this->render('viewdetailCallHistory', array (
			'modelpotentialcustomers' => $modelpotentialcustomers,
			'model' => $model,
			
		));
	}
	//拨打跟进电话
	public function actionCallFollowUpPhone($status_id) {
		$model = $this->loadModel($status_id);

		$user_id = Yii :: app()->user->id > 0 ? Yii :: app()->user->id : $_POST['Status']['agent_id'];
		if (isset ($_POST['Status'])) {
			$modelstatus = new Status;
			$modelstatus->attributes = $_POST['Status'];
			$modelstatus->status = $_POST['status'];

			if ($_POST['status'] == '6') {
				$modelstatus->follow_up = $_POST['follow_up'];
				$modelstatus->sign_up_date = $_POST['sign_up_date1'];
				$modelstatus->callback_date_and_time = "";
				$modelstatus->contract_expire_date = $_POST['contract_expire_date1'];
				$modelstatus->package = $_POST['package1'];
			} else
				if ($_POST['status'] == '7') {
					$modelstatus->sign_up_date = $_POST['sign_up_date'];
					$modelstatus->callback_date_and_time = "";
					$modelstatus->contract_expire_date = $_POST['contract_expire_date'];
					$modelstatus->package = $_POST['package'];
				}
			if ($modelstatus->save())
				PotentialCustomers :: model()->updateAll(array (
					'mark' => 0
				), 'potential_customers_id=:potential_customers_id', array (
					':potential_customers_id' => $_POST['Status']['customer_id']
				));
			PotentialCustomers :: model()->updateAll(array (
				'first_name' => $_POST['first_name'],
				'last_name' => $_POST['last_name'],
				'gender' => $_POST['PotentialCustomers']['gender'],
				'mobile' => $_POST['mobile'],
				'address' => $_POST['address'],
				'email' => $_POST['email'],
				'post_code' => $_POST['post_code'],
				'update_user' => $user_id,
				'update_time' => date("Y-m-d H:i:s")
			), 'potential_customers_id=:potential_customers_id', array (
				':potential_customers_id' => $_POST['Status']['customer_id']
			));
			//把跟进前的通话记录的跟进id换成新增的通话记录的id
			$model->followup_statusid = $modelstatus->status_id;
			$model->save();
			$this->redirect(array (
				'about'
			));
		}

		$modelcustomers = PotentialCustomers :: model()->findByPk($model->customer_id);
		$model->last_called_date_and_time = date("Y-m-d H:i:s");
		//通过客户的手机号查询客户的中奖信息
		$surveyuser = $this->getsurveyuserinfo($modelcustomers->mobile);
		$this->render('callFollowUpPhone', array (
			'modelcustomers' => $modelcustomers,
			'surveyuser' => $surveyuser,
			'model' => $model,
			
		));
	}

	public function actionAbout() {
		$this->render('about');
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new Status;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset ($_POST['Status'])) {
			$model->attributes = $_POST['Status'];
			if ($model->save())
				$this->redirect(array (
					'view',
					'id' => $model->status_id
				));
		}

		$this->render('create', array (
			'model' => $model,
			
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = $this->loadModel($id);
		$modelPotentialCustomers =PotentialCustomers:: model()->findByPk($model->customer_id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset ($_POST['Status'])) {
			$model->attributes = $_POST['Status'];
			$modelPotentialCustomers->address=$_POST['PotentialCustomers']['address'];
			if ($model->save())
			{
			$modelPotentialCustomers->save();	
			$level=User::model()->getlevel(Yii::app()->user->id);
			if($level==12)
			{
					$this->redirect(array (
					'callLoginAdmin',
					'agent_id' => Yii::app()->user->id
				));
			}else{
					$this->redirect(array (
					'admin',
					'id' => $model->status_id
				));
			}
			}			
		}

		$this->render('update', array (
			'model' => $model,
			'modelPotentialCustomers'=>$modelPotentialCustomers
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if (!isset ($_GET['ajax']))
			$this->redirect(isset ($_POST['returnUrl']) ? $_POST['returnUrl'] : array (
				'admin'
			));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Status');
		$this->render('index', array (
			'dataProvider' => $dataProvider,
			
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Status('search');
		$model->unsetAttributes(); // clear any default values
		if (isset ($_GET['Status'])) {
			$model->attributes = $_GET['Status']; //列表搜索
			$last_called_date_and_time = $_GET['last_called_date_and_time'];

		} else {
			$model->campaign_id = $_REQUEST['campaign_id'];
			$model->last_called_date_and_time = date("Y-m-d");
		}
		$this->render('admin', array (
			'model' => $model,
			'last_called_date_and_time' => $last_called_date_and_time,
			
		));
	}

	//查找通话记录
	public function actionCallLoginAdmin() {
		$model = new Status('search');
		$model->unsetAttributes(); // clear any default values
		if (isset ($_GET['Status'])) {
			$model->attributes = $_GET['Status']; //列表搜索
			$last_called_date_and_time = $_GET['last_called_date_and_time'];
		} else {
			$model->agent_id = $_REQUEST['agent_id'];
			$model->last_called_date_and_time = date("Y-m-d");
		}
		$this->render('callLoginAdmin', array (
			'model' => $model,
			'last_called_date_and_time' => $last_called_date_and_time,
		));
	}

	//电话销售人员发送邮件给客户
	public function actionSendNewLetter() {
		
		$email_to = Yii :: app()->request->getparam('email_to');
		$templet = Yii :: app()->request->getparam('templet');
		$attachments = Yii :: app()->request->getparam('attachments');
		$i = Status :: model()->sendEmail($email_to,$templet,$attachments);
		if ($i) {
			echo 'Send New Letter Success';
		} else {
			echo 'Send New Letter Failer';
		}

	}
	//电话销售人员发送短信给客户
	public function actionSendSms() {
		$mobile = Yii :: app()->request->getparam('mobile');
		$smscontent = Yii :: app()->request->getparam('smscontent');
		$post_data = array (
			'method' => "sendMessages",
			'username' => "abc",
			'password' => "123456",
			'mobile' => $mobile,
			'api_id' => 53,
			'text' => $smscontent
		);
		$url ="http://sms.webnova.com.au/api/webnova_sms_api_lib.php";
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($ch, CURLOPT_POST, 1);
		// 把post的变量加上
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		$output = curl_exec($ch);
			// 调试使用		
		if ($output === FALSE) {
			$output = "cURL Error: " . curl_error ( $ch );
		} else {		
		if (isset ( Yii::app ()->request->isAjaxRequest )) {
			echo 'Send Sms Success';
			} else {
			echo 'Send Sms Failer';
			}
		}
		curl_close ( $ch );	
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Status the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id) {
		$model = Status :: model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
	/**
	 * Performs the AJAX validation.
	 * @param Status $model the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset ($_POST['ajax']) && $_POST['ajax'] === 'status-form') {
			echo CActiveForm :: validate($model);
			Yii :: app()->end();
		}
	}
	function getOneCustomer($potential_customers_list_id_list, $campaign_id, $model,$user_id) {
		//随机取出一笔没有被打过的客户
		$sqlstatus = "SELECT * FROM zy_potential_customers WHERE potential_customers_id NOT IN(
				SELECT a.potential_customers_id FROM `zy_potential_customers` a LEFT JOIN `zy_potential_status` b 
				ON a.potential_customers_id=b.customer_id 
				WHERE  a.potential_customers_list_id IN ($potential_customers_list_id_list) AND b.campaign_id=$campaign_id AND b.`status`='1' AND HOUR( TIMEDIFF( NOW(),  b.`last_called_date_and_time`) )>4 OR b.`status`>'1' ) AND potential_customers_list_id IN ($potential_customers_list_id_list) and mark=0 ORDER BY RAND() LIMIT 1";
		$resultstatus = Yii :: app()->db->createCommand($sqlstatus)->queryAll();
		if (count($resultstatus) != 0) {
			$modelcustomers = new PotentialCustomers;
			$modelcustomers->attributes = $resultstatus[0];
			$modelcustomers->potential_customers_id = $resultstatus[0]['potential_customers_id'];
			$model->last_called_date_and_time = date("Y-m-d H:i:s");
			$sqlupdate = "update zy_potential_customers set mark=1,update_user=".$user_id.",update_time=now() where potential_customers_id=" . $resultstatus[0]['potential_customers_id'];

			Yii :: app()->db->createCommand($sqlupdate)->execute();
			return $modelcustomers;
		}
		return false;
	}

	//通过客户的手机号到zy_survey_user表里查找该用户的信息
	function getsurveyuserinfo($mobile) {
		$surveyuser = SurveyUser :: model()->find('mobile=:mobile', array (
			':mobile' => $mobile
		));
		return $surveyuser;
	}

	/**
	 * 汇总报告跳转
	 */
	public function actionReports() {
		$model = new Status('search');
		if(empty($_REQUEST['Status']['last_called_date_and_time'])){
			$model->last_called_date_and_time =date('Y-m-d');
		}else{
			$model->last_called_date_and_time = $_REQUEST['Status']['last_called_date_and_time'];
		}
		//callback_date_and_time 字段纯属借用赋值方便,无其他意义
		if(empty($_REQUEST['Status']['last_called_date_and_time'])){

			$model->callback_date_and_time =date('Y-m-d',strtotime("+1 days"));

		}else{

			$model->callback_date_and_time = $_REQUEST['Status']['callback_date_and_time'];

		}
		
		$this->render('report', array (
			'model' => $model,
		));
	}

}